package org.codeart.ioc.context;

import org.codeart.ioc.reader.BeanDefinitionReader;
import org.codeart.ioc.support.BeanDefinitionRegistry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractApplicationContext implements ApplicationContext {

    // 声明解析器变量
    protected BeanDefinitionReader beanDefinitionReader;

    // 定义存储 Bean 对象的 Map 集合
    protected final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(128);

    // 声明配置文件类路径的变量
    protected String configLocation;

    @Override
    public void refresh() {
        // 加载beanDefinition对象
        try {
            beanDefinitionReader.loadBeanDefinitions(configLocation);
            // 初始化bean
            finishBeanInitialization();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * bean初始化
     *
     * @throws Exception 异常
     */
    protected void finishBeanInitialization() throws Exception {
        // 获取对应的注册表对象
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();

        // 获取beanDefinition对象
        String[] beanNames = registry.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            //进行bean的初始化
            getBean(beanName);
        }
    }
}
